package business.seguranca;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;



public class Encriptacao
{
	private static String algoritimo = "AES";
	private byte[] chave = new String("AC/KCfjxZf5M0eUz").getBytes();
	
	public String encriptar(String valor) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
	{
		Cipher cipher = Cipher.getInstance(algoritimo);
		SecretKeySpec secretKeySpec = new SecretKeySpec(chave, algoritimo);
		
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		
		byte[] valorBytes = valor.getBytes("UTF8");
		
		byte[] valorEncriptado = cipher.doFinal(valorBytes);
		
		Base64 encoderDecoder = new Base64();
		
		return encoderDecoder.encodeToString(valorEncriptado);
	}
	
	public String decriptar(String valor) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
	{
		Cipher cipher = Cipher.getInstance(algoritimo);
		SecretKeySpec secretKeySpec = new SecretKeySpec(chave, algoritimo);
		
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
		
		Base64 decoder = new Base64();
		byte[] valorBytes = decoder.decode(valor);
		
		byte[] valorBytesDecriptado = cipher.doFinal(valorBytes);
		
		String valorDecriptado = new String(valorBytesDecriptado, "UTF8");
		
		return valorDecriptado;
	}
	
	public String gerarChave() throws NoSuchAlgorithmException, UnsupportedEncodingException 
	{
		KeyGenerator generator;
		generator = KeyGenerator.getInstance(algoritimo);
		generator.init(new SecureRandom());
		Key key = generator.generateKey();
		
		return Base64.encodeBase64String(key.getEncoded());
	}

}
